package org.example.filter;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.Util.JwtUtil;
import org.example.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
//@WebFilter(urlPatterns = "/*")
@Slf4j
public class DeptsFilter implements Filter {

    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 将请求和响应都强转为HttpServletRequest和HttpServletResponse
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (request.getRequestURI().contains("/login")) {
            filterChain.doFilter(request, response);
            return;
        }

        //判断是否携带token
        String token = request.getHeader("token");
        if (token == null) {
            // 输出为空日志
            log.info("token为空");
            Result error = Result.error("NOT_LOGIN");
            // 通过fastjson将Result对象转换为json字符串
            String json = JSONObject.toJSONString(error);
            response.getWriter().write(json);
            return;
        }
        log.info("token不为空");
        try {
            jwtUtil.checkToken(token);
        } catch (Exception e) {
            log.info("token验证失败");
            Result error = Result.error("NOT_LOGIN");
            // 通过fastjson将Result对象转换为json字符串
            String json = JSONObject.toJSONString(error);
            response.getWriter().write(json);
            return;
        }
        log.info("token验证成功");
        filterChain.doFilter(request, response);
    }
}
